﻿using System;
using System.Diagnostics.Contracts;
using IMModel.Domain.Common;
using System.Collections.Generic;

namespace IMModel.Domain
{
    /// <summary>
    /// Показатель в периоде
    /// </summary>
    partial class CharacteristicTerm : IRespondentIndexVector, ICacheble, IItem
    {
        #region ICacheble Members
        private Dictionary<IndexContext, RespondentIndexCollection> _respondentIndexCaches;

        private RespondentIndexCollection _respondentVolumesCache;
        //private RespondentIndexCollection _respondentIndexCache;
        //private Dictionary<IndexContext, RespondentIndexCollection> _respondentVolumesCaches;

        public void Invalidate()
        {
            Contract.Ensures(_respondentIndexCaches == null);

            _respondentIndexCaches = null;
            //GradationCharacteristics.Invalidate();
            if (InsteadOf != null) InsteadOf.Invalidate();
        }

        #endregion

        #region IRespondentIndexVector Members

        public RespondentIndexCollection Indexes
        {
            get
            {
                CDebug.Write("IndexContext.Current");
                return CalcIndexes(IndexContext.Current);
                //CalcIndexes();
                //return _respondentIndexCache;
            }
        }

        /// <summary>
        /// Получает индекс заданного респондента
        /// </summary>
        /// <param name="respondent"></param>
        /// <returns></returns>
        public double this[Respondent respondent]
        {
            get
            {
                Contract.Requires(Indexes != null);
                Contract.Requires(respondent != null);

                return Indexes[respondent];
            }
        }

        //private void CalcIndexes()
        //{
        //    if (_respondentIndexCache != null) return;
        //    CalcValues();
        //}

        //private void CalcValues()
        //{
        //    Contract.Requires(_gradationVolumesResolver != null);
        //    CharacteristicTerm currCharactericTerm = this;

        //    while (currCharactericTerm != null)
        //    {
        //        if (currCharactericTerm.IsValidInPeriod(Term))
        //        {
        //            _respondentIndexCache += GetTermVolumes(null, currCharactericTerm, Term);
        //        }
        //        currCharactericTerm = currCharactericTerm.InsteadOf;
        //    }
        //}
        #endregion

        public RespondentIndexCollection CalcIndexes(IndexContext сontext)
        {
            return CCache.Get(ref _respondentIndexCaches, сontext, () =>
                сontext.Policy.GetIndexes(сontext, this));
        }
    }
}